const {	createApp } = Vue
createApp({
	data() {
		return {
			apiServer: `${window.location.protocol}//${window.location.hostname}:8089/`,
			// apiServer: `http://192.168.168.4:8089/`,
			unSavedNaotuKey: "NAOTU-UN-SAVED-KEY",
			mySavedNaotuListKey: "NAOTU-MY-SAVED-KEY",
			mySavedNaotuList: [],
			curNaotu: {id:null},
			oldMinderData: null,
			showSavedNaotuList: !1,
			naotuTips: "",
			userinfo: {},
			loginTitle: '登录',
			myNaotuButton: "我的脑图",
			checked: false
		}
	},
	//组件渲染完成
	mounted() {
		let t = this;
		angular.module("kityminderContainer", ["kityminderEditor"]).controller("MainController", [
			"$scope",
			function(e) {
				e.initEditor = function(e, a) {
					window.editor = e, window.minder = a, t.listenChange()
				}
			}
		]), angular.bootstrap("#kityminderContainer");
		this.userinfo = JSON.parse(localStorage.getItem('userinfo'));
		if (this.userinfo == null) {
			window.location.href = "login.html";
			return;
		}
		if (this.userinfo != null && this.userinfo.code == 200) {
			this.loginTitle = `退出登录：${this.userinfo.data.nickname}`;
		}
		//this.newNaotu();
		let e = localStorage.getItem(this.unSavedNaotuKey) || "";
		e && (e = JSON.parse(e)).data.root.children.length && (this.naotuTips =
				`上次有一个编辑未保存到服务器的脑图【${e.title}】，可以<span class="x-load">继续编辑</span>`), window
			.addEventListener("keydown", t => {
				(t.metaKey || t.ctrlKey) && 83 === t.keyCode && (this.saveNaotu(), t.preventDefault(),t.stopPropagation())
			}, !1)
	},
	methods: {
		setNaotuTips(text) {  // 由ajax回调函数调用，设置脑图提示信息
			this.naotuTips = text;
		},
		getMySavedNaotuList(naotu) {  // 由ajax回调函数调用，刷新脑图列表
			for(let i = 0; i < naotu.length; i++){
				if(!naotu[i].mapShare){
					naotu[i].mapShare = {"shareId":false};
				}
			}
			this.mySavedNaotuList = naotu;
		},
		loginButton() {  // 退出登录
			this.userinfo.data = {};
			this.userinfo.code = 500;
			localStorage.setItem("userinfo", JSON.stringify(this.userinfo));
			window.location.href = "login.html";
		},
		listenChange() {  // 监听当前脑图的改变
			window.editor.minder.on("contentchange", () => {
				const t = editor.minder.exportJson();
				this.getCurrentNaotu();
				json_diff(this.oldMinderData, t).length > 0 && t.root.children.length && (
					this.oldMinderData = t,
					localStorage.setItem(this.unSavedNaotuKey, JSON.stringify(this.curNaotu)),
					this.naotuTips =
					`脑图【${this.curNaotu.title}】于 ${this.dateFormat1(1*new Date)} 修改，但未保存到服务器！`
				)
			})
		},
		loadUnSaved() {  // 从localstorage载入上次未保存的脑图
			this.$refs.tipsBar.querySelector("span.x-load") && (this.curNaotu = JSON.parse(localStorage
					.getItem(this.unSavedNaotuKey) ||
					"{}"), editor.minder.importJson(this.curNaotu.data), this.naotuTips =
				`脑图【${this.curNaotu.title}】于 ${this.dateFormat1(1*new Date)} 修改，但未保存到服务器！`)
		},
		getCurrentNaotu() { //保存脑图到缓存区【this.curNaotu】
			this.curNaotu.title = editor.minder.getMinderTitle();
			this.curNaotu.data = editor.minder.exportJson();
		},
		setCurrentNaotu(data) { // 由【编辑/保存】按钮函数调用
			this.curNaotu = {
				id: data.id,
				deleted: data.deleted,
				createBy: data.createBy,
				updateBy: data.updateBy,
				createdAt: data.createdAt,
				updatedAt: data.updatedAt,
				userId: data.userId,
				title: data.title,
				data: JSON.parse(data.data)
			};
			editor.minder.importJson(this.curNaotu.data);
			localStorage.setItem(this.unSavedNaotuKey, "");
		},
		newNaotu() { // 新建脑图
			let e = localStorage.getItem(this.unSavedNaotuKey) || "";
			if (e && !window.confirm(`脑图【${this.curNaotu.title}】没有保存到服务器，是否继续打开新文档？`)) {
				return false;
			}
			editor.minder.getMinderTitle();
			editor.minder.importData("text", "中心主题");
			this.curNaotu = {
				id: null,
				title: editor.minder.getMinderTitle(),
				data: editor.minder.exportJson(),
				deleted: false,
			};
			localStorage.setItem(this.unSavedNaotuKey, "");
			this.naotuTips = "";
		},
		saveNaotu() {  // 保存脑图到云端
			this.getCurrentNaotu();
			let t = this;
			t.naotuTips = `脑图【${t.curNaotu.title}】保存中！`;
			$.ajax({
				type: "POST",
				url: `${t.apiServer}map`,
				dataType: "json",
				headers: {
					"minder-token": t.userinfo.data.tokenInfo.tokenValue
				},
				data: {
					"id": t.curNaotu.id,
					"title": t.curNaotu.title,
					"data": JSON.stringify(t.curNaotu.data),
					"deleted": "0",
					"userId": t.userinfo.data.tokenInfo.loginId
				},
				success: function(data) {
					t.setNaotuTips(
						`${t.dateFormat1(1*new Date)} 脑图【${t.curNaotu.title}】保存成功！`);
					localStorage.setItem(t.unSavedNaotuKey, "");
					t.setCurrentNaotu(data.data);
					t.myNaotu(false);
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					t.setNaotuTips(`脑图【${t.curNaotu.title}】保存失败！`);
				}
			});
		},
		importNaotu() {  // 导入脑图支持【json】格式
			let t = document.createElement("input");
			t.type = "file", t.accept = "application/json", t.style.cssText =
				"position:absolute;top:-100px;left:-100px", t.addEventListener(
					"change", t => {
						let e = new FileReader;
						e.onload = (t => {
							let e = t.target.result;
							try {
								let t = JSON.parse(e);
								t instanceof Array || (t = [t]);
								let a = 0,
									i = 0;
								t.map(t => (this.mySavedNaotuList.some(e => e.id === t.id && (e
										.updated_at < t.updated_at && (e = t, a++),
										t._replaced = !0, !0)), t)).filter(t => !t._replaced).map(
										t => {
											this.mySavedNaotuList.unshift(t), i++
										}), this.naotuTips =
									`文件累计${t.length}条，共导入${a+i}条，其中替换${a}条，新增${i}条`, this
									.curNaotu =
									t[0], editor.minder
									.importJson(this.curNaotu.data)
							} catch (t) {}
						}), e.readAsText(t.target.files[0])
					}, !1), document.body.appendChild(t), t.click()
		},
		exportNaotu(t, e) {  // 导出脑图【支持图片和json】
			if ("png" === t) editor.minder.exportData("png").then(t => {
				let e = document.createElement("a");
				e.setAttribute("download", `FH-${editor.minder.getMinderTitle()}.png`), e
					.setAttribute("href", t), e.style.cssText =
					"position:absolute;top:-1000px;left:-1000px;", document.body.appendChild(e), e
					.click(), e.remove()
			});
			else if ("json" === t) {
				let t = null,
					a = `FeHelper-Naotu-${1*new Date}.json`;
				if ("all" === e) t = new Blob([JSON.stringify(this.mySavedNaotuList)], {
					type: "application/octet-stream"
				});
				else {
					let e = this.getCurrentNaotu();
					t = new Blob([JSON.stringify(e)], {
						type: "application/octet-stream"
					}), a = `FeHelper-Naotu-${e.title}.json`
				}
				let i = document.createElement("a");
				i.setAttribute("download", a), i.setAttribute("href", URL.createObjectURL(t)), i.style
					.cssText =
					"position:absolute;top:-1000px;left:-1000px;", document.body.appendChild(i), i
					.click(),
					i.remove()
			}
		},
		myNaotu(flag) {  // 获取云脑图列表
			if (flag) {
				this.showSavedNaotuList = !this.showSavedNaotuList
				if (this.showSavedNaotuList) {
					this.myNaotuButton = "关闭列表";
				} else {
					this.myNaotuButton = "我的脑图";
					return true;
				}
			}
			let t = this;
			$.ajax({
				type: "GET",
				url: `${t.apiServer}map/list`,
				dataType: "json",
				headers: {
					"minder-token": t.userinfo.data.tokenInfo.tokenValue
				},
				success: function(data) {
					t.getMySavedNaotuList(data.data);
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					alert("获取列表信息失败！");
				}
			});
		},
		alert(shareId){  // 获取共享链接
			alert(`共享链接：【${window.location.protocol}//${window.location.host}/share.html?${shareId}】`);
		},
		check(el, shareId) {  // 切换分享状态
			let t = this;
			checkStatus = el.target.checked;
			$.ajax({
				type: "PUT",
				url: `${t.apiServer}map/share/${shareId}`,
				dataType: "json",
				headers: {
					"minder-token": t.userinfo.data.tokenInfo.tokenValue
				},
				data: {
					"shared": checkStatus
				},
				success: function(data) {
					t.setNaotuTips(`${checkStatus? "分享已开启" : "分享已关闭"}`);
					t.myNaotu(false);
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					alert(XMLHttpRequest.responseJSON.msg);
					t.myNaotu(false);
					el.target.checked = checkStatus;
				}
			});
		},
		editNaotu(id) {  // 编辑列表中的云脑图
			this.myNaotu(true);
			let e = localStorage.getItem(this.unSavedNaotuKey) || "";
			if (e && !window.confirm(`脑图【${this.curNaotu.title}】没有保存到服务器，是否继续打开新文档？`)) {
				return false;
			}
			let t = this;
			$.ajax({
				type: "GET",
				url: `${t.apiServer}map/${id}`,
				dataType: "json",
				headers: {
					"minder-token": t.userinfo.data.tokenInfo.tokenValue
				},
				success: function(data) {
					t.setCurrentNaotu(data.data);
					t.setNaotuTips("");
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					alert("打开云脑图失败！");
				}
			});
		},
		deleteNaotu(id,title) {  // 删除云脑图
			if (!window.confirm(`脑图【${title}】将被放入回收站？`)) {return;}
			let t = this;
			if (id == t.curNaotu.id) {
				t.newNaotu();
			}
			$.ajax({
				type: "DELETE",
				url: `${t.apiServer}map/${id}`,
				dataType: "json",
				headers: {
					"minder-token": t.userinfo.data.tokenInfo.tokenValue
				},
				success: function(data) {
					t.myNaotu(false);
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					alert("删除失败！");
				}
			});
		},
		dateFormat(dateStr) {  // 格式化来自服务器的时间
			// 2022-11-03T20:18:41.099
			if (dateStr == null) {
				return "";
			}
			let dateDS = dateStr.split('T');
			return `${dateDS[0]}  ${dateDS[1].split('.')[0]}`;
		},
		dateFormat1(t) {  // 格式化前端生成的时间
			let e = "yyyy-MM-dd HH:mm:ss",
				a = function(t, e) {
					let a = "",
						i = t < 0,
						o = String(Math.abs(t));
					return o.length < e && (a = new Array(e - o.length + 1).join("0")), (i ? "-" : "") +
						a +
						o
				},
				i = function(t, a) {
					e = e.replace(t, a)
				},
				o = (t = new Date(t)).getFullYear(),
				n = t.getMonth() + 1,
				s = t.getDate(),
				r = t.getHours(),
				d = t.getMinutes(),
				u = t.getSeconds(),
				l = t.getMilliseconds();
			return i(/yyyy/g, a(o, 4)), i(/yy/g, a(parseInt(o.toString().slice(2), 10), 2)), i(/MM/g, a(n,
				2)), i(/M/g, n), i(
				/dd/g, a(s, 2)), i(/d/g, s), i(/HH/g, a(r, 2)), i(/H/g, r), i(/hh/g, a(r % 12, 2)), i(
				/h/g, r % 12), i(/mm/g, a(
				d, 2)), i(/m/g, d), i(/ss/g, a(u, 2)), i(/s/g, u), i(/SSS/g, a(l, 3)), i(/S/g, l), e
		}
	}
}).mount('#mainContainer')